package com.nvn.androidapp.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.nvn.androidapp.R;
import com.nvn.androidapp.Objects.Document;

public class InputInforFragment extends Fragment{
	private static final String KEY_CONTENT = "InputInforFragment:Data";
	private String data = "";
	private EditText edt_title, edt_des, edt_price, edt_expDate, edt_contact;
	private Document doc;
	
	public static InputInforFragment newInstance(Document doc) {
		InputInforFragment fragment = new InputInforFragment();
		StringBuilder sb = new StringBuilder();
		fragment.doc = doc;
		if(-1 != doc.getID()){
			sb.append(doc.getTitle()).append("#")
				.append(doc.getDes()).append("#")
				.append(doc.getPrice()).append("#")
				.append(doc.getExDate()).append("#")
				.append(doc.getContact());
			fragment.data = sb.toString();
		}
        

        return fragment;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View v = inflater.inflate(R.layout.layout_input_infor, container, false);
		
		edt_title = (EditText)v.findViewById(R.id.edt_title);
		edt_des = (EditText)v.findViewById(R.id.edt_des);
		edt_price = (EditText)v.findViewById(R.id.edt_price);
		edt_expDate = (EditText)v.findViewById(R.id.edt_expDate);
		edt_contact = (EditText)v.findViewById(R.id.edt_contact);
		
		if(data.contains("#")){
			String[] str = data.split("#");
			try{
				edt_title.setText(str[0]);
			}catch(Exception e){}
			try{
				edt_des.setText(str[1]);
			}catch(Exception e){}
			try{
				edt_price.setText(str[2]);
			}catch(Exception e){}
			try{
				edt_expDate.setText(str[3]);
			}catch(Exception e){}
			try{
				edt_contact.setText(str[4]);
			}catch(Exception e){}
		}
		
		return v;
	}

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
        	data = savedInstanceState.getString(KEY_CONTENT);
        }
    }
	
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, data);
    }
	
	public Document saveData(){
		doc.setTitle(edt_title.getText().toString().trim());
		doc.setDes(edt_des.getText().toString().trim());
		doc.setPrice(edt_price.getText().toString().trim());
		doc.setExDate(edt_expDate.getText().toString().trim());
		doc.setContact(edt_contact.getText().toString().trim());
		
		return doc;
	}
	
	public void setExpDate(String date){
		edt_expDate.setText(date);
	}
}
